package com.iot.ht.controller.htaction;

import com.iot.core.annotation.Auth;
import com.iot.core.annotation.Log;
import com.iot.core.data.BasePageDtQto;
import com.iot.core.data.entity.HtAction;
import com.iot.core.data.mapper.HtActionMapper;
import com.iot.core.enums.AuthType;
import com.iot.core.manager.htcls.HtClsManager;
import com.iot.core.manager.htctl.HtCtlManager;
import com.mybatisflex.core.paginate.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import static com.iot.core.data.entity.table.HtActionTableDef.HT_ACTION;
import static com.iot.core.data.entity.table.HtUserLoginTableDef.HT_USER_LOGIN;

@Slf4j
@RestController
@RequestMapping("/htaction")
@Tag(name = "API管理", description = "")
public class HtActionController {
    @Autowired
    HtActionMapper htActionMapper;

    @Auth(authType = AuthType.Login)
    @Log(logNeed = false,logTemplete ="",logPin = true,logPout = true)
    @PostMapping("/page")
    @Operation(summary = "API分页", description = "")
    public Page<HtAction> page(@RequestBody BasePageDtQto qm) throws Exception {
        var qw=htActionMapper.getQueryWrapper();
        if(StringUtils.hasText(qm.getDtb() )){
            qw.and( HT_ACTION.EDT_DT.ge(qm.getDB()));
        }

        if(StringUtils.hasText(qm.getDte() )){
            qw.and( HT_ACTION.EDT_DT.lt(qm.getDE()));
        }

        if(StringUtils.hasText(qm.getKey() )){
            if(StringUtils.hasText(qm.getKey() )){
                qw.and( HT_ACTION.CTL_FULL_NAME.like(qm.getKey())
                        .or( HT_ACTION.NAME.like(qm.getKey()) )
                        .or( HT_ACTION.FULL_URL.like(qm.getKey()) )
                );

            }
        }
        var sort=qm.getSort();
        qw.orderBy( sort.toString()  );
        var r=htActionMapper.page(  qm,qw );
        return r;
    }

    @Auth(authType = AuthType.Auth)
    @Log(logNeed = true,logTemplete ="",logPin = true,logPout = true)
    @PostMapping("/refreshtodb")
    @Operation(summary = "刷新Action", description = "")
    public  int refreshToDb(){
        var prjName="com.iot.core";
        HtClsManager.getInstance().refreshToDb(prjName);
        HtCtlManager.getInstance().refreshToDb(prjName);

        prjName="com.iot.ht";
        HtClsManager.getInstance().refreshToDb(prjName);
        HtCtlManager.getInstance().refreshToDb(prjName);

        return 1;
    }

}
